package com.wuchengdong.web.service.impl;

import com.wuchengdong.web.mapper.DashboardMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DashboardService {

    @Autowired
    private DashboardMapper dashboardMapper;

    public Map<String, Object> getDashboardData() {
        Map<String, Object> result = new HashMap<>();

        // 今日数据
        result.put("dashboardData", dashboardMapper.getTodayStats());

        // 最近7天趋势（Java 端补全日期缺失）
        result.put("trendData", buildTrendMap("appointments", dashboardMapper.getAppointmentTrend()));
        result.put("statData", buildTrendMap("orders", dashboardMapper.getOrderTrend()));

        return result;
    }

    private Map<String, Object> buildTrendMap(String valueKey, List<Map<String, Object>> rawData) {
        List<String> dates = new ArrayList<>();
        List<Integer> values = new ArrayList<>();

        LocalDate today = LocalDate.now();
        for (int i = 6; i >= 0; i--) {
            String date = today.minusDays(i).toString();
            dates.add(date);

            // 查找是否有匹配日期的数据
            Integer count = rawData.stream()
                .filter(row -> date.equals(row.get("date").toString()))
                .map(row -> ((Number) row.get(valueKey)).intValue())
                .findFirst()
                .orElse(0);

            values.add(count);
        }

        Map<String, Object> trend = new HashMap<>();
        trend.put("dates", dates);
        trend.put("appointments".equals(valueKey) ? "appointments" : "values", values);
        return trend;
    }
}
